package cn.px.service.sb.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.px.dao.enums.SysFileTypeEnum;
import com.github.pagehelper.PageHelper;
import cn.px.common.bean.AbstractPageResultBean;
import cn.px.common.exception.BusinessException;
import cn.px.common.util.IdGeneratorUtils;
import cn.px.common.util.ListUtils;
import cn.px.dao.bean.MyPage;
import cn.px.dao.dto.sb.SbMeasureLogDTO;
import cn.px.dao.entity.check.CheckProjectStandardRelation;
import cn.px.dao.entity.sb.SbInfoMeasure;
import cn.px.dao.entity.sb.SbMeasureLog;
import cn.px.dao.entity.upms.SysFile;
import cn.px.dao.mapper.sb.SbInfoMeasureMapper;
import cn.px.dao.mapper.sb.SbMeasureLogMapper;
import cn.px.dao.mapper.upms.SysFileMapper;
import cn.px.dao.vo.query.sb.SbMeasureLogVO;
import cn.px.service.base.impl.BaseServiceImpl;
import cn.px.service.sb.SbMeasureLogService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.weekend.Weekend;

import java.util.List;

/**
 * @Description 点检标准 service 实现类
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2020,北京乾元坤和科技有限公司 All rights reserved.
 */
@AllArgsConstructor
@Service("sbMeasureLogService")
public class SbMeasureLogServiceImpl extends BaseServiceImpl<SbMeasureLogMapper, SbMeasureLog, SbMeasureLogDTO> implements SbMeasureLogService {
    private SbInfoMeasureMapper sbInfoMeasureMapper;
    private final SysFileMapper sysFileMapper;
    @Override
    public boolean cascadingDeleteByKey(String id) {
        int result = mapper.deleteByPrimaryKey(id);
        Weekend<CheckProjectStandardRelation> weekend = new Weekend<>(CheckProjectStandardRelation.class);
        weekend.weekendCriteria().andEqualTo(CheckProjectStandardRelation::getStandardId,id);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int batchDelete(List<String> ids) {

        ids.forEach(id -> {
            cascadingDeleteByKey(id);
        });
        return 1;
    }

    @Override
    public List<SbMeasureLogVO> selectList(SbMeasureLogDTO record) {
        return mapper.selectList(record);
    }

    @Override
    public AbstractPageResultBean<SbMeasureLog> selectPageInfo(SbMeasureLogDTO record, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        AbstractPageResultBean<SbMeasureLog> pageInfo = new MyPage(mapper.selectList(record));
        return pageInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SbMeasureLog saveModelByDTO(SbMeasureLogDTO model) {
        SbMeasureLog sbMeasureLog = super.saveModelByDTO(model);
        model.setId(sbMeasureLog.getId());
        // 更新设备下次检定日期
        SbInfoMeasure sbInfo = sbInfoMeasureMapper.selectByPrimaryKey(model.getSbId());
        sbInfo.setCheckDate(model.getLastDate());
        Integer checkPeriod = 12;// 默认12个月
        if(sbInfo.getCheckPeriod() != null){
            checkPeriod = sbInfo.getCheckPeriod();
        }else{
            throw new BusinessException("检定设备的检定周期未设置，无法计算下次检定日期，请先设置");
        }
        sbInfo.setNextCheckDate(model.getLastDate().minusMonths(-checkPeriod).minusDays(1));
        sbInfo.setZaiz(model.getName());// 检定单位
        sbInfo.setSbdh(model.getNo());// 检定编号
        sbInfo.setRemark(model.getRemark());// 备注
        sbInfo.setDph(model.getRequirement());// 检定人
        sbInfo.setStatus(model.getSbStatus());// 每次检定后，状态变更也要更新
        sbInfoMeasureMapper.updateByPrimaryKey(sbInfo);

        // 保存文件
        this.saveFile(model);
        // 保存参数
       /* List<CheckStandardParamDTO> paramList = model.getParamList();
        paramList.forEach(item -> {
            item.setStandardId(checkStandard.getId());
        });
        paramService.saveModelListByDTO(paramList);*/
        return sbMeasureLog;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void modModelByDTO(SbMeasureLogDTO model) {
        super.modModelByDTO(model);
        // 更新设备下次检定日期
        SbInfoMeasure sbInfo = sbInfoMeasureMapper.selectByPrimaryKeyForUpdate(model.getSbId());
        sbInfo.setCheckDate(model.getLastDate());

        Integer checkPeriod = 12;// 默认12个月
        if(sbInfo.getCheckPeriod() != null){
            checkPeriod = sbInfo.getCheckPeriod();
        }else{
            throw new BusinessException("检定设备的检定周期未设置，无法计算下次检定日期，请先设置");
        }
        sbInfo.setNextCheckDate(model.getLastDate().minusMonths(-checkPeriod).minusDays(1));
        sbInfo.setZaiz(model.getName());// 检定单位
        sbInfo.setSbdh(model.getNo());// 检定编号
        sbInfo.setRemark(model.getRemark());// 备注
        sbInfo.setDph(model.getRequirement());// 检定人
        sbInfo.setStatus(model.getSbStatus());// 每次检定后，状态变更也要更新
        sbInfoMeasureMapper.updateByPrimaryKey(sbInfo);

        // 保存文件
        this.saveFile(model);
        // 保存参数
  /*      List<CheckStandardParamDTO> paramList = model.getParamList();
        paramList.forEach(item -> {
            item.setStandardId(model.getId());
        });
        paramService.saveModelListByDTO(paramList);*/
    }

    private void saveFile(SbMeasureLogDTO model) {
        Weekend<SysFile> weekend = new Weekend<>(SysFile.class);
        weekend.weekendCriteria().andEqualTo(SysFile::getTargetId, model.getId());
        sysFileMapper.deleteByExample(weekend);
        List<SysFile> checkImgList = model.getCheckImgList();
        List<SysFile> checkFileList = model.getCheckFileList();
        List<SysFile> list = ListUtils.newArrayList();
        if (CollectionUtil.isNotEmpty(checkImgList)) {
            checkImgList.forEach(item -> {
                item.setType(SysFileTypeEnum.Sb_MEASURE_IMGS.getValue());
                item.setId(IdGeneratorUtils.getObjectId());
                item.setTargetId(model.getId());
                list.add(item);
            });
        }
        if (CollectionUtil.isNotEmpty(checkFileList)) {
            checkFileList.forEach(item -> {
                item.setType(SysFileTypeEnum.Sb_MEASURE_FILES.getValue());
                item.setId(IdGeneratorUtils.getObjectId());
                item.setTargetId(model.getId());
                list.add(item);
            });
        }
        if (CollectionUtil.isNotEmpty(list)) {
            sysFileMapper.insertListforComplex(list);
        }
    }

    @Override
    public SbMeasureLog getModelById(Object id) {
        SbMeasureLog checkStandard = super.getModelById(id);
  /*      Weekend<CheckStandardParam> weekend = new Weekend<>(CheckStandardParam.class);
        weekend.weekendCriteria().andEqualTo(CheckStandardParam::getStandardId, id);
        List<CheckStandardParam> paramList = paramMapper.selectByExample(weekend);
        checkStandard.setParamList(paramList);*/

        SbInfoMeasure sbInfo = sbInfoMeasureMapper.selectByPrimaryKey(checkStandard.getSbId());
        checkStandard.setSbNo(sbInfo.getCardNo());
        checkStandard.setSbModel(sbInfo.getModel());
        checkStandard.setSbName(sbInfo.getName());
        checkStandard.setCheckPeriod(sbInfo.getCheckPeriod());
        checkStandard.setCheckDate(sbInfo.getCheckDate());
        checkStandard.setNextCheckDate(sbInfo.getNextCheckDate());
        checkStandard.setFdjxh(sbInfo.getFdjxh());
        checkStandard.setSbStatus(sbInfo.getStatus());
        Weekend<SysFile> weekendFile = new Weekend<>(SysFile.class);
        weekendFile.weekendCriteria().andEqualTo(SysFile::getTargetId, checkStandard.getId());
        List<SysFile> sysFiles = sysFileMapper.selectByExample(weekendFile);
        List<SysFile> checkImgList = ListUtils.newArrayList();
        List<SysFile> checkFileList = ListUtils.newArrayList();
        sysFiles.forEach(item -> {
            if (item.getType().equals( SysFileTypeEnum.Sb_MEASURE_IMGS.getValue())) {
                checkImgList.add(item);
            }
            if (item.getType().equals( SysFileTypeEnum.Sb_MEASURE_FILES.getValue())) {
                checkFileList.add(item);
            }
        });
        checkStandard.setCheckImgList(checkImgList);
        checkStandard.setCheckFileList(checkFileList);
        return checkStandard;
    }
}
